#include "teacher_information_dialog.h"
#include "ui_teacher_information_dialog.h"

#include <QRegExpValidator>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QMessageBox>
#include <QTimer>
#include "operate_login_information.h"
#include "global_variant.h"


TeacherInformationDialog::TeacherInformationDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::TeacherInformationDialog)
{
    ui->setupUi(this);

    initializeSetStyleSheet();

    connect(ui->submitPushButton, &QPushButton::clicked,
            this, [&](){
        if(ui->teacherIdLineEdit->text().size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("请先输入教师编号，再提交信息，谢谢！"));
            QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
            infoBox->show();

            ui->teacherIdLineEdit->setFocus();
            return;
        }

        if(ui->nameLineEdit->text().size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("请先输入姓名，再提交信息，谢谢！"));
            QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
            infoBox->show();

            ui->nameLineEdit->setFocus();
            return;
        }

        QString password = ui->passwordLineEdit->text();
        QString affrimPassword = ui->affirmPasswordLineEdit->text();
        if(password.size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("密码为空，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->passwordLineEdit->setFocus();
            return;
        }
        if(affrimPassword.size() == 0){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("确认密码为空，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->affirmPasswordLineEdit->setFocus();
            return;
        }

        //判密码一致性
        qDebug()<<"affrimPassword:"<<affrimPassword;
        qDebug()<<"password:"<<password;
        if(affrimPassword != password){
            ui->passwordLineEdit->clear();
            ui->affirmPasswordLineEdit->clear();
            ui->passwordLineEdit->setFocus();
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("新密码和确认密码不一致，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();
            return;
        }

        //密码长度过短
        if(password.size() < 8){
            QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("密码长度过短，请重新输入！"));
            QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
            infoBox->show();

            ui->passwordLineEdit->clear();
            ui->affirmPasswordLineEdit->clear();

            ui->passwordLineEdit->setFocus();
            return;
        }

        OperateLoginInformation operateLoginInformation;
        if(m_dialogStatus == DialogStatus::InsertInformation){
            QString account = ui->teacherIdLineEdit->text();

            int databaseOperateResult = operateLoginInformation.registerAccount(account, password);

            if(databaseOperateResult == DatabaseOperateStatus::RegisterSuccessType){
                if(insertTeacherInformation2Database()){
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Information, tr("信息提示"), tr("成功新增数据。"));
                    QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();

                    emit teacherInformationDialog2MainInterface();

                    this->close();
                }else{
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误提示"), tr("请重新检查数据，新增数据失败！"));
                    QTimer::singleShot(3000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();
                }

            }else if(databaseOperateResult == DatabaseOperateStatus::RegisterFailType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("账号注册失败！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();

                ui->teacherIdLineEdit->clear();
                ui->teacherIdLineEdit->setFocus();
            }else if(databaseOperateResult == DatabaseOperateStatus::AccountAlreadyExistentType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("该用户编号已被注册，请重新输入！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();

                ui->teacherIdLineEdit->clear();
                ui->teacherIdLineEdit->setFocus();
            }

        }else if(m_dialogStatus == DialogStatus::AlterInformation){
            OperateLoginInformation operateLoginInformation;
            int databaseOperateResult = operateLoginInformation.alterAccount(m_originalTeacherId, ui->teacherIdLineEdit->text(), password);
            if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterSuccessType ){
                if(updateTeacherInformation2Database()){
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Information, tr("信息提示"), tr("成功修改数据。"));
                    QTimer::singleShot(2000, infoBox,&QMessageBox::deleteLater);
                    infoBox->show();

                    emit teacherInformationDialog2MainInterface();

                    this->close();
                }else{
                    QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("错误信息"), tr("用户数据添加失败！"));
                    QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                    infoBox->show();
                }
            }else if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterFailType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("修改账号信息失败！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();
            }else if(databaseOperateResult == DatabaseOperateStatus::AlterRegisterNoAffectedType){
                QMessageBox* infoBox = new QMessageBox(QMessageBox::Critical, tr("信息提示"), tr("账号信息没有修改！"));
                QTimer::singleShot(2000, infoBox, &QMessageBox::deleteLater);
                infoBox->show();
            }
        }


    });
}

TeacherInformationDialog::~TeacherInformationDialog()
{
    delete ui;
}

void TeacherInformationDialog::initializeSetStyleSheet()
{
    QRegExp passwordRegx("[a-zA-Z0-9]+$");
    //编号
    QValidator* accountValidator = new QRegExpValidator(passwordRegx, ui->teacherIdLineEdit);
    ui->teacherIdLineEdit->setValidator(accountValidator);
    ui->teacherIdLineEdit->setMaxLength(65);

    //密码
    QValidator* passwordValidator2 = new QRegExpValidator(passwordRegx, ui->passwordLineEdit);
    ui->passwordLineEdit->setValidator(passwordValidator2);
    ui->passwordLineEdit->setMaxLength(65);

    //确认密码
    QValidator* passwordValidator3 = new QRegExpValidator(passwordRegx, ui->affirmPasswordLineEdit);
    ui->affirmPasswordLineEdit->setValidator(passwordValidator3);
    ui->affirmPasswordLineEdit->setMaxLength(65);

    //密码为暗文输入
    ui->passwordLineEdit->setEchoMode(QLineEdit::Password);
    //密码为暗文输入
    ui->affirmPasswordLineEdit->setEchoMode(QLineEdit::Password);
}

bool TeacherInformationDialog::insertTeacherInformation2Database()
{
    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");
    if(db.transaction()){
        QSqlQuery query(db);
        QString tmpSql = QString("INSERT INTO teacher_information(teacher_id, name, role_id)")
                         + QString(" VALUES(?,?,?)");
        query.prepare(tmpSql);

        QVariantList teacher_id;
        QVariantList name;
        QVariantList role_id;

        teacher_id<<ui->teacherIdLineEdit->text();
        name<<ui->nameLineEdit->text();
        role_id<<QString("2");

        query.addBindValue(teacher_id);
        query.addBindValue(name);
        query.addBindValue(role_id);

        if(!query.execBatch()){
            qDebug()<<query.lastError().databaseText();

            return false;
        }

        tmpSql = QString("INSERT INTO permission_manage_information(user_id, role_id) VALUES(\'%1\', \'%2\')").arg(ui->teacherIdLineEdit->text()).arg(QString("2"));
        if(!query.exec(tmpSql)){
            qDebug()<<query.lastError().databaseText();

            return false;
        }

        if(!db.commit())//提交事务
        {
            if(!db.rollback())
                qDebug() << "db.lastError()"<<db.lastError().databaseText(); //回滚
            return false;
        }else{//事务执行成功
            return true;
        }
    }
    return false;
}

bool TeacherInformationDialog::updateTeacherInformation2Database()
{
    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");
    if(db.transaction()){
        QVariantList teacher_id;
        QVariantList name;
        QVariantList teacher_id_original;

        QSqlQuery query(db);
        //UPDATE table_anem SET column_name1 = value1, column_name2 = value2... WHERE
        QString tmpSql = QString("UPDATE teacher_information SET teacher_id = ?, name = ?")
                         + QString(" WHERE teacher_id = ?");

        qDebug()<<tmpSql;
        query.prepare(tmpSql);

        teacher_id<<ui->teacherIdLineEdit->text();
        name<<ui->nameLineEdit->text();

        teacher_id_original<<m_originalTeacherId;

        query.addBindValue(teacher_id);
        query.addBindValue(name);
        query.addBindValue(teacher_id_original);

        if(!query.execBatch()){
            qDebug()<<query.lastError().databaseText();

            return false;
        }

        if(m_originalTeacherId != ui->teacherIdLineEdit->text()){
            tmpSql = QString("UPDATE permission_manage_information SET user_id= \'%1\' WHERE user_id = \'%2\'").arg(ui->teacherIdLineEdit->text()).arg(m_originalTeacherId);
            if(!query.exec(tmpSql)){
                qDebug()<<query.lastError().databaseText();

                return false;
            }
        }

        if(!db.commit())//提交事务
        {
            if(!db.rollback())
                qDebug() << "db.lastError()"<<db.lastError().databaseText(); //回滚
            return false;
        }else{//事务执行成功
            return true;
        }
    }
    return false;
}

void TeacherInformationDialog::initializeAlterTeacherInformationDialog(QString teacher_id)
{
    this->setWindowTitle("教师信息修改");

    m_originalTeacherId = teacher_id;

    m_dialogStatus = DialogStatus::AlterInformation;

    QSqlDatabase db = QSqlDatabase::database("mysql_connection1");

    QSqlQuery query = QSqlQuery(db);

    QString tmpSql = QString("SELECT teacher_id, name FROM teacher_information WHERE teacher_id =  \'%1\'").arg(m_originalTeacherId);
    if(!query.exec(tmpSql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        while(query.next()){
            ui->teacherIdLineEdit->setText(query.value(0).toString());
            ui->nameLineEdit->setText(query.value(1).toString());
        }
    }

    tmpSql = QString("SELECT password FROM login_information WHERE account = \'%1\'").arg(m_originalTeacherId);

    if(!query.exec(tmpSql)){
        qDebug()<<query.lastError().databaseText();
    }else{
        QString password;
        while(query.next()){
            password = query.value(0).toString();
        }
        ui->passwordLineEdit->setText(password);
        ui->affirmPasswordLineEdit->setText(password);

        m_originalPassword = password;
        qDebug()<<"m_originalPassword:"<<m_originalPassword.size();
    }

    this->exec();
}

void TeacherInformationDialog::initializeInsertTeacherInformationDialog()
{
    this->setWindowTitle("教师信息新增");

    m_dialogStatus = DialogStatus::InsertInformation;

    ui->teacherIdLineEdit->clear();
    ui->nameLineEdit->clear();
    ui->passwordLineEdit->clear();
    ui->affirmPasswordLineEdit->clear();


    this->exec();
}
